<template>
  <template v-if=" User!=null ">
    <van-cell title="昵称" :value="User.username"/>
    <van-cell title="星球编号" :value="User.planetCode"/>
    <van-cell title="个人信息" is-link to="/user/info"/>
    <van-cell title="我创建的队伍" is-link to="/user/team/create"/>
    <van-cell title="我加入的队伍" is-link to="/user/team/join"/>
    <van-cell title="账号与安全" is-link to="/user/security"/>
  </template>
  <van-button type="default" size="large" round @click="doLogout">退出登录</van-button>

</template>

<script setup lang="ts">
import {onMounted, ref, onActivated} from "vue";
import {showConfirmDialog, showFailToast} from "vant";
import {getCurrentUser} from "../../sevices/User.ts";
import 'vant/lib/index.css';
import {userLogout} from "../../api/User.ts";
import {useRouter} from "vue-router";


const router = useRouter();

const User = ref();

// 封装获取用户信息的方法（复用）
const fetchUserInfo = async () => {
  const result = await getCurrentUser();
  if (result) {
    User.value = result;
    // 性别转换保持不变
    User.value.gender = result.gender === 0 ? '男' : '女';
  } else {
    showFailToast('获取用户信息失败');
  }
};

// 首次挂载时执行
onMounted(() => {
  fetchUserInfo();
});

// 关键：返回页面时（无论是否缓存），重新获取数据
onActivated(() => {
  fetchUserInfo(); // 强制刷新最新数据
});

// 退出登录
const doLogout = async () => {
  showConfirmDialog({
    title: '退出登录',
    message:
        '您确定要退出登录吗',
  }).then( async () => {
    const result = await userLogout();
    console.log(result);
    // @ts-ignore
    if (result?.code === 0 && result?.data === 1) {
      await router.push('/user/login')
    } else {
      // @ts-ignore
      showFailToast('退出失败' + (result?.description ? `${result.description}` : ''));
    }
  }).catch(() => {

  });

}


</script>

<style scoped>

</style>